// --------------------------------------------开始
var drawControl;
var dataSource;
var gaoDePoi;

var $table;

//限定区域
var drawEntity;

//查询结果
var bootstrapList = [];

//上一次请求参数，用于 下一页使用
var lastArg;
//当前页面业务相关
function initWorkPoi() {


    $("#txtCity").citypicker({
        simple: true,
        level: 'city',
        province: '广东省',
        city: '深圳市',
        //district: '蜀山区',
    });

    gaoDePoi = new GaodePOI({
        key: [
            "027187040fa924e56048468aaa77b62c",
            "2e6ca4aeb6867fb637a5bee8333e5d3a",
            "b185732970a4487de104fa71ef575f29",
            "81825d9f2bafbb14f235d2779be90c0f",
            "f2fedb9b08ae13d22f1692cd472d345e",
        ]
    });

    dataSource = new Cesium.CustomDataSource();
    viewer.dataSources.add(dataSource);

    $table = $('#table');
    $table.bootstrapTable({
        height: 300,
        singleSelect: true, //单选
        pagination: false,
        iconsPrefix: 'fa',
        columns: [
            {
                title: '序号',
                sortable: true,
                editable: false,
                align: 'left',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'name',
                title: '企业名称',
            },
            {
                field: 'address',
                title: '地址',
            },
            {
                field: 'tel',
                title: '联系电话',
                sortable: true,
                editable: false,
                align: 'left',
                formatter: function (value, row) {
                    if (value)
                        return value;
                    else
                        return "";
                }
            }
        ],
        onClickRow: function (item, $element, field) {
            var entity = item._entity;
            if (entity == null) {
                toastr.warning(item.name + " 无经纬度坐标信息！");
                return;
            }
            var position = entity.position._value;
            viewer.mars.centerPoint(position, {
                radius: 2000, //距离目标点的距离
                pitch: -50, //相机方向
                duration: 3,
                complete: function (e) { //飞行完成回调方法
                    viewer.mars.popup.show(entity); //显示popup

                }
            });
        }
    });

    var selectType;
    $('input:radio[name="queryContent"]').change(function () {
        selectType = $(this).val();

        switch (selectType) {
            default: //按城市
                $(".queryByCity").show();
                $(".queryByDraw").hide();
                break;
            case "2": //当前视角范围
                $(".queryByCity").hide();
                $(".queryByDraw").hide();
                break;
            case "3": //按范围
                $(".queryByCity").hide();
                $(".queryByDraw").show();
                break;
        }
    });

    $("#query").click(function () {
        clearAll(selectType == "3");
        bootstrapList = [];
        switch (selectType) {
            default: //按城市
                var dnnm = $("#txtCity").data('citypicker').getCode();
                // var dmmc = $("#txtCity").data('citypicker').getVal();

                loadData({
                    page: 1,
                    city: dnnm,
                });
                break;
            case "2": //当前视角范围
                var extent = mars3d.point.getExtent(viewer);
                loadData({
                    page: 1,
                    points: [
                        [extent.xmin, extent.ymin],
                        [extent.xmin, extent.ymax],
                        [extent.xmax, extent.ymax],
                        [extent.xmax, extent.ymin]
                    ],
                });
                break;
            case "3": //按范围
                if (!drawEntity) {
                    toastr.warning("请绘制限定范围！");
                    return;
                }
                loadData({
                    page: 1,
                    entity: drawEntity,
                });
                break;
        }

    });


    drawControl = new mars3d.Draw(viewer, {
        hasEdit: false
    });


    //框选查询 矩形
    $("#drawRectangle").click(function () {
        clearAll();
        drawControl.startDraw({
            "type": "rectangle",
            "style": {
                "color": "#00FF00",
                "opacity": 0.3,
                "outline": true,
                "outlineColor": "#ffffff",
                "clampToGround": true
            },
            success: function (entity) {
                drawEntity = entity;
            }
        });
    });

    //框选查询   多边
    $("#drawPolygon").click(function () {
        clearAll();
        drawControl.startDraw({
            "type": "polygon",
            "style": {
                "color": "#00FF00",
                "opacity": 0.3,
                "outline": true,
                "outlineColor": "#ffffff",
                "clampToGround": true
            },
            success: function (entity) {
                drawEntity = entity;
            }
        });
    });
    //框选查询   圆
    $("#drawCircle").click(function () {
        clearAll();
        drawControl.startDraw({
            "type": "circle",
            "style": {
                "color": "#00FF00",
                "opacity": 0.3,
                "outline": true,
                "outlineColor": "#ffffff",
                "clampToGround": true
            },
            success: function (entity) {
                drawEntity = entity;
            }
        });
    });

    $("#clearDraw").click(function () {


        clearAll();
    });
    //加载更多- 下一页
    $("#loadMore").click(function () {
        if (!lastArg) return;

        lastArg.page++;
        loadData(lastArg);
    });


    // if(location.search){
    //     document.querySelector("#queryText").value = decodeURI(location.search.replace(/^.+?\=/ig,''));
    //     var dnnm = $("#txtCity").data('citypicker').getCode();

    //     loadData({
    //         page: 1,
    //         city:dnnm
    //     });
    // }
}
function loadData(arg) {
    var queryVal = $.trim($("#queryText").val());
    if (queryVal.length == 0) {
        haoutil.msg("请输入 名称 关键字筛选数据！")
        return;
    }
    haoutil.loading.show();
    arg.count = 25 //count 每页数量
    arg.text = queryVal;
    arg.success = function (res) {
        $("#resultView").show();
        var data = res.list;
        bootstrapList = bootstrapList.concat(data);
        $table.bootstrapTable("append", data)
        $("#count").html(bootstrapList.length);
        $("#allcount").html(res.allcount);
        if (bootstrapList.length >= res.allcount || res.allcount < 25 || data.length == 0) {
            $("#loadMore").hide();
        } else {
            $("#loadMore").show();
        }
        addEntity(data);
        haoutil.loading.close();
    }
    arg.error = function (msg) {
        window.toastr.error(msg);
        haoutil.loading.close();
    }
    gaoDePoi.query(arg);
    lastArg = arg;
}
function clearAll(noClearDraw) {
    lastArg = null;
    bootstrapList = [];
    $table.bootstrapTable("load", bootstrapList);
    $("#resultView").hide();
    $("#loadMore").hide();
    if (dataSource) dataSource.entities.removeAll();
    if (!noClearDraw && drawControl) {
        drawControl.clearDraw();
        drawEntity = null;
    }
    viewer.mars.popup.close();
}


function choose(a){
    // top.showChooseLocation(a);
    window.parent.postMessage(a, "http://121.37.224.139:8091/");
}

function addEntity(data) {
    for (var i = 0; i < data.length; i++) {
        var item = data[i];

        //==================构建图上目标单击后显示div=================
        var inHtml = '<div class="mars-popup-titile">' + item.name + '</div><div class="mars-popup-content" >';
        var type = $.trim(item.type);
        if (type != '') inHtml += '<div><label>类别</label>' + type + '</div>';
        var xzqh = $.trim(item.xzqh);
        if (xzqh != '') inHtml += '<div><label>区域</label>' + xzqh + '</div>';
        var tel = $.trim(item.tel);
        if (tel != '') inHtml += '<div><label>电话</label>' + tel + '</div>';
        var address = $.trim(item.address);
        if (address != '') inHtml += '<div><label>地址</label>' + address + '</div>';
        inHtml += '<div><button onclick="choose(`['+item.x+','+item.y+']`)"  style="color: black;">选择该点坐标</button></div></div>';

        var entity = dataSource.entities.add({
            position: Cesium.Cartesian3.fromDegrees(item.x, item.y),
            point: {
                color: new Cesium.Color.fromCssColorString("#3388ff"),
                pixelSize: 10,
                outlineColor: new Cesium.Color.fromCssColorString("#ffffff"),
                outlineWidth: 2,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, //贴地
                scaleByDistance: new Cesium.NearFarScalar(1000, 1, 1000000, 0.1)
            },
            label: {
                text: item.name,
                font: '20px 楷体',
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                fillColor: Cesium.Color.AZURE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -10), //偏移量  
                heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND, //是地形上方的高度
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000)
            },
            popup: {
                html: inHtml,
                anchor: [0, -12],
            }
        });

        item._entity = entity;
    }
}
// --------------------------------------------结束

/* 2017-12-7 10:33:50 | 修改 木遥（QQ：516584683） */
//loading bar
var loadingBar = document.getElementById('loadbar');
var oldTime = new Date().getTime();
var thisWidget = {};
var tileSets=[];
var geojsonData=[];
var jsonSpatialData=[];
window.jsonSpatialData = jsonSpatialData
//父页面tree reload
function run() {
    var curTime = new Date().getTime();
    if (curTime - oldTime >= 3500) {
        loadingBar.className = "";
        if (curTime - oldTime >= 3550) {
            loadingBar.className = "ins";
            oldTime = curTime;
        }
    }
    if (Window.LOADING_FLAG == true) {
        clearInterval(loadIdx);
    }
}
function loaderOK() {
    $("#loadOverlay").hide();
    $('#loadbar').removeClass('ins');
    Window.LOADING_FLAG = true;
}
var loadIdx = setInterval(run, 100);


//地图
$(document).ready(function () {
    if (!mars3d.util.webglreport()) {
        toastr.error('系统检测到您当前使用的浏览器WebGL功能无效');
        layer.open({
            type: 1,
            title: "当前浏览器WebGL功能无效",
            skin: "layer-mars-dialog animation-scale-up",
            resize: false,
            area: ['600px', '200px'], //宽高
            content: '<div style="margin: 20px;"><h3>系统检测到您使用的浏览器WebGL功能无效！</h3>  <p>1、请您检查浏览器版本，安装使用最新版chrome、火狐或IE11以上浏览器！</p> <p>2、WebGL支持取决于GPU支持，请保证客户端电脑已安装最新显卡驱动程序！</p><p>3、如果上两步骤没有解决问题，说明您的电脑需要更换了！</p></div>'
        });
    }
    initUI();
    initMap();
});
// 窗口自适应 
$(window).on('resize', function() {

     $(window.document).find("iframe").css("height",($(window.document).find("#layui-layer1").height()-40)+'px');

}).resize();

function removeMask() {
    $("#mask").remove();
}

var viewer;
window.viewer = viewer
//初始化地图
function initMap() {
    var request = haoutil.system.getRequest();

    var configfile = "config/sceneManage.json";
    if (request.config)
        configfile = request.config;

    haoutil.loading.show();

    var r = new Cesium.Resource({
        url: "http://10.253.102.69/gw/ESRI/Map/SZ_IMG02_2019/{z}/{x}/{y}",
        headers: {
            'szvsud-license-key': 'E7YieQ1tH6Q4CjoZAmI98Fc5mbayuHfXAjkKyZS3bZM=',
        },
    });

    mars3d.createMap({
        id: 'cesiumContainer',
        url: configfile + "?time=20190418",
        imageryProvider: new Cesium.UrlTemplateImageryProvider({
            url: r
        }),
        //infoBox: false,     //是否显示点击要素之后显示的信息  【也可以在config.json中配置】
        //sceneMode: Cesium.SceneMode.SCENE2D,
        layerToMap: layerToMap,
        success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行
            //欢迎UI关闭处理
            setTimeout(removeMask, 3000);
            loaderOK();
            haoutil.loading.hide();

            //记录viewer
            viewer = _viewer;

            //初始化widget管理器
            var hasAnimation = true;
            if (haoutil.isutil.isNotNull(request.widget)) {
                jsondata.widget.widgetsAtStart.push({
                    uri: request.widget,
                    request: request
                });
                hasAnimation = false;
            }
            mars3d.widget.init(_viewer, jsondata.widget);

            //如果有xyz传参，进行定位
            if (haoutil.isutil.isNotNull(request.x)
                && haoutil.isutil.isNotNull(request.y)) {
                viewer.mars.centerAt(request, { duration: 0, isWgs84: true });
            }

            // if (hasAnimation)
            //     viewer.mars.openFlyAnimation();//开场动画

            initWork(_viewer);
            initWorkPoi();
            
            testWork(_viewer); //测试专用

            //新增内容


        }
    });
}

//图层预览
 function load3Dtiles(dataUrl,id) {
     //加载三维模型，此方法可设置相机初始视角
     var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
         url: dataUrl,
         maximumScreenSpaceError: 2,
         dynamicScreenSpaceError : true,
     }));
     tileset.modelMatrix = Cesium.Matrix4.fromArray([
         1.0, 0.0, 0.0, 0.0,
         0.0, 1.0, 0.0, 0.0,
         0.0, 0.0, 1.0, 0.0,
         0.0, 0.0, 0.0, 1.0
     ]);
     tileset.readyPromise.then(function (tileset) {
         tileSets[id]=tileset;
         viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.5, -0.5, tileset.boundingSphere.radius * 0.5));
     }).otherwise(function (error) {
         // console.log(error);
         parent.layer.msg("渲染失败，请检查服务地址是否合法", {icon: 5});
     });
     return tileset;
}

//自定义图层地图服务要素图层预览
 function loadGeoJson(dataUrl,id) {
     var dataSource = new Cesium.GeoJsonDataSource();
     var geojsonOptions = {
         clampToGround : true
     };
     dataSource.load(dataUrl,geojsonOptions).then(function(data) {
         // var entities = dataSource.entities.entities;
     });
     this.viewer.dataSources.add(dataSource).then(function (data) {
         viewer.zoomTo(data);
         geojsonData[id]=data;
     }).otherwise(function (error) {
         parent.layer.alert("渲染失败，请检查服务地址是否合法", {icon: 4,title:"提示"});
     });
 }

//空间模型geojson数据加载
function load3DGeoJson(json,id){
    this.drawControl = new mars3d.Draw(this.viewer, {
        hasEdit: false,
        nameTooltip: true,
    });
    setTimeout ( ()=>{
        jsonSpatialData[id]=this.drawControl.jsonToEntity(json,true,true);//视角定位指向实体

    },200)
}

//清除图层
function removeEntityById(id){
    if(this.geojsonData[id]){
        this.viewer.dataSources.remove(this.geojsonData[id]);
        delete this.geojsonData[id];
    }
    if(this.tileSets[id]){
        this.viewer.scene.primitives.remove(this.tileSets[id]);
        delete this.tileSets[id];
    }
    if(this.jsonSpatialData[id]){
        var spatialDataLength=jsonSpatialData[id].length;
        for(var i=0;i<spatialDataLength;i++){
            this.drawControl.deleteEntity(this.jsonSpatialData[id][i]);
        }
        delete this.jsonSpatialData[id];
    }
}
//定位
function centerEntityById(id){
    if(this.geojsonData[id]){
        this.viewer.zoomTo(this.geojsonData[id]);
    }
    if(this.tileSets[id]){
        this.viewer.zoomTo(this.tileSets[id], new Cesium.HeadingPitchRange(0.5, -0.5, this.tileSets[id].boundingSphere.radius * 0.5));
    }
    if(this.jsonSpatialData[id]){
        this.viewer.mars.flyTo(jsonSpatialData[id][0])
    }
}

function clear() {
    window.viewer.dataSources.removeAll();
    window.viewer.scene.primitives.removeAll();
    window.viewer.dataSource.entities.removeAll();
    // this.dataSource.entities.removeAll();
}
function removeGeoJson() {
    window.viewer.dataSources.removeAll();
}
function remove3DGeoJson() {
    window.viewer.dataSources.removeAll();
    // this.dataSource.entities.removeAll();
}
function remove3Dtiles() {
    window.viewer.scene.primitives.removeAll();
}

//创建空间模型
function spatialModelCreate(){
    mars3d.widget.activate({
        uri: 'view/sceneManage/spatialModelCreate/widget.js',
        name:"创建空间模型"
    });
}

//空间模型创建后，弹框点击保存事件
function get3DGeoJson() {
 /*   this.drawControl = new mars3d.Draw(this.viewer, {
        hasEdit: false,
        nameTooltip: true,
    });
    return this.drawControl.toGeoJSON();*/
    var spatialModelCreate = mars3d.widget.getClass('view/sceneManage/spatialModelCreate/widget.js');
    return spatialModelCreate.getGeoJson();
}

//空间模型创建后，关闭弹框
function close_spatialModelCreate() {
    //关闭时清除绘制的图层
    var spatialModelCreate = mars3d.widget.getClass('view/sceneManage/spatialModelCreate/widget.js');
    spatialModelCreate.deleteAll();
    mars3d.widget.disable(
         'view/sceneManage/spatialModelCreate/widget.js', false
    );
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

var sceneId=getUrlParam("sceneId");
//场景导览弹框激活
function sceneNavigate() {
    mars3d.widget.activate({
        uri: 'widgets/roamLine/widget.js',
        name:"场景导览",
        sceneId:sceneId
    });
}
//场景导览弹框关闭
function close_sceneNavigate() {
    mars3d.widget.disable(
        'widgets/roamLine/widget.js',false);
}
//UI界面相关
function initUI() {
    // haoutil.oneMsg('首次访问系统无缓存会略慢，请耐心等待！', 'load3d_tip');


}


//当前页面业务相关
function initWork(viewer) {
    // haoutil.oneMsg('如果未出现地球，是因为地形加载失败，请刷新重新加载！', 'terrain_tip');

    // 禁用默认的实体双击动作。
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //webgl渲染失败后，刷新页面
    //viewer.scene.renderError.addEventListener(function (scene, error) {
    //    window.location.reload();
    //});


    //移动设备上禁掉以下几个选项，可以相对更加流畅
    if (!haoutil.system.isPCBroswer()) {
        viewer.targetFrameRate = 20;        //限制帧率
        viewer.requestRenderMode = true;    //取消实时渲染
        viewer.scene.fog.enable = false;
        viewer.scene.skyAtmosphere.show = false;
        viewer.scene.fxaa = false;
    }

    //IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
        viewer.targetFrameRate = 20;        //限制帧率
        viewer.requestRenderMode = true;    //取消实时渲染
    }

    //更改配置，性能优化
    viewer.scene.logarithmicDepthBuffer = false;

    //二三维切换不用动画
    if (viewer.sceneModePicker)
        viewer.sceneModePicker.viewModel.duration = 0.0;

    //设置操作习惯,更换中键和右键
    //viewer.scene.screenSpaceCameraController.tiltEventTypes = [
    //    Cesium.CameraEventType.RIGHT_DRAG, Cesium.CameraEventType.PINCH,
    //    { eventType: Cesium.CameraEventType.LEFT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL },
    //    { eventType: Cesium.CameraEventType.RIGHT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL }
    //];
    //viewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.MIDDLE_DRAG, Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH];


    //3dtiles模型的单体化高亮，在ex/featureViewer.js处理
    featureViewer.install(viewer);


}

//config中非底层类库封装类，可以在此加入进行实例化
function layerToMap(item, viewer, layer) {
    switch (item.type) {
        //case "s3m"://超图S3M数据加载
        //    return new S3MLayer(item, viewer);
        //    break;
    }
}


//测试一些功能
function testWork(viewer){
    //绑定confgi.json标绘类型图层 单击事件
    // var layerWork = this.viewer.mars.getLayer(303011, 'id');
    // layerWork.config.click =function(entity){
    //     //var name =entity.attribute.name;

    //     mars3d.widget.activate({
    //         uri: 'widgetsTS/qyDetailsView/widget.js',
    //         attribute: entity.attribute,
    //     });
    // }

}

//绑定图层管理有2种添加方式
/**
    第1种是框架支持的配置信息的，按照下面方式添加
    var json = {
        "pid": 40,
        "name": "代码添加图层test",
        "type": "wms",
        "url": "http://gisserver.tianditu.com/TDTService/region/wms",
        "layers": "030100",
        "parameters": {
            "transparent": "true",
            "format": "image/png"
        },
        "center": { "y": 17.571877, "x": 114.258325, "z": 6591684.1, "heading": 352.3, "pitch": -74.3, "roll": 0.1 },
        "visible": true
    };
    mars3d.layer.createLayer(json, viewer);
    bindToLayerControl(json);
**/

/** 第2种是完全自定义的，在回调方法中写自己相关代码，可参考widgetsTS\qyPoint\widgts.js代码
bindToLayerControl({
    pid: 30,
    name: '企业',
    mydata:null, //自行赋值
    visible: true,
    onAdd: function () {//显示回调
        //这里把数据this.mydata添加到地图上
    },
    onRemove: function () {//隐藏回调
        //这里把数据this.mydata从地图上移除

    },
    onCenterAt: function (duration) {//定位回调

    },
});
**/

//绑定图层管理
function bindToLayerControl(options) {
    if (options._layer == null) {
        var _visible = options.visible;
        delete options.visible;

        var layer = new mars3d.layer.BaseLayer(options, viewer);
        layer._visible = _visible;
        options._layer = layer;
    }

    var manageLayersWidget = mars3d.widget.getClass('widgets/manageLayers/widget.js');
    if (manageLayersWidget) {
        manageLayersWidget.addOverlay(options);
    }
    else {
        viewer.gisdata.config.operationallayers.push(options);
    }
    return options._layer;
}
//取消绑定图层管理
function unbindLayerControl(name) {
    var manageLayersWidget = mars3d.widget.getClass('widgets/manageLayers/widget.js');
    if (manageLayersWidget) {
        manageLayersWidget.removeLayer(name);
    } else {
        var operationallayersCfg = viewer.gisdata.config.operationallayers;
        for (var i = 0; i < operationallayersCfg.length; i++) {
            var item = operationallayersCfg[i];
            if (item.name == name) {
                operationallayersCfg.splice(i, 1);
                break;
            }
        }
    }
}

//外部页面调用
function activateWidget(item) {
    mars3d.widget.activate(item);
}
function disableWidget(item) {
    mars3d.widget.disable(item);
}
function activateFunByMenu(fun) {
    eval(fun);
}
